#!/bin/sh

usage() {
	script=${0##*/}
	echo "
$script - create ext2/3/4 file

Syntax:
  $script [-ext2|-ext3|-ext4] <SIZE_MB> <OUTPUT_FILE>
  
  default = ext4
"
	
	exit
}

for i in $@ ; do
	case $1 in
		-ext2) SFFS=ext2 ; EXT=2fs ; shift ;;
		-ext3) SFFS=ext3 ; EXT=3fs ; shift ;;
		-ext4) SFFS=ext4 ; EXT=4fs ; shift ;;
		-*) echo 'unknown param: $1' ; exit 1 ;;
	esac
done

[ ! "$SFFS" ] && SFFS=ext4 && EXT=4fs

[ ! "$1" -o ! "$2" ] && usage

SIZEPFILE=$1
shift
OUTFILE="$@".$EXT

dd if=/dev/zero of="$OUTFILE" bs=1M count=$SIZEPFILE || {
	rm -f "$OUTFILE"
	exit 1
}

DEVLOOP="$(losetup -f)"
FSCK_DEV=$DEVLOOP
losetup -v $DEVLOOP $OUTFILE

mke2fs -t $SFFS -m 0 -E nodiscard -F $FSCK_DEV || {
	rm -f "$OUTFILE"
	exit 1
}

e2fsck -f -y -E discard $FSCK_DEV

### END ###